package cn.com.kh.batch.callback;

import cn.com.kh.FDDUtils;
import cn.com.kh.KHUtil;
import cn.com.kh.batch.BatchDeal_Utils;
import cn.com.kh.batch.BatchData_Utils;
import cn.com.kh.result.FddResult;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

/**
 * @Title: authCallback
 * @Description: 认证回调
 */
public class authCallback {
    private static final Log log = LogFactory.getLog(authCallback.class);

    private static int i_Num = 0;

    // 认证回调
    public static JSONObject doAuthCallback(JdbcTemplate jt, String callback_Type, String rec_Guid, String Cc_CustomerId, String callPram) {
        JSONObject res_Json = JSONObject.fromObject(new FddResult(FddResult.SUCCESS, "认证回调处理完成", "Init"));
        try {
            // 接收客户端调用参数
            JSONObject bizContentJson = FDDUtils.callbackParse(callPram).getJSONObject("bizContent");
            log.debug("⚖法大大回调 认证回调 处理开始 rec_Guid:" + rec_Guid + " Cc_CustomerId:" + Cc_CustomerId + " bizContentJson:" + bizContentJson);

            String status = FDDUtils.GetSFJV(bizContentJson, "status"); // 获取状态
            String statusDesc = FDDUtils.GetSFJV(bizContentJson, "statusDesc"); // 获取状态描述
            String auditFailReason = FDDUtils.GetSFJV(bizContentJson, "auditFailReason"); // 获取失败原因

            // 将回调结果更新到对应的客户信息中
            i_Num = jt.update("Update Customer Set Fdd_Status = ?, Fdd_Reason = ?, Modifiedby = 'SELITE', Modifieddate = Now() Where CustomerId = ?", status, statusDesc + (KHUtil.isNull(auditFailReason) ? "(" + auditFailReason + ")" : ""), Cc_CustomerId);
            log.debug("⚖法大大回调 认证回调 -将回调结果更新到对应的客户信息中-更新DB数据:" + i_Num);

            // 将回调结果更新到认证Log回调表
            i_Num = jt.update("Update Sys_Oper_Log_Auth Set Status = ?, Statusdesc = ?, Remark = ?, Callback_Time = Now() Where Push_Type = '认证' And Rec_Guid = ? And Customer_Id = ?", status, statusDesc, auditFailReason, rec_Guid, Cc_CustomerId);
            log.debug("⚖法大大回调 认证回调 -将回调结果更新到认证Log回调表-更新DB数据:" + i_Num);

            // 如果无失败原因说明认证通过
            if (KHUtil.isNull(auditFailReason)) {
                // 查询是否还有未认证通过的客户
                List<Map<String, Object>> selectExits = jt.queryForList("Select R1.Oper_Id From Sys_Oper_Log_Auth R1 Left Join Customer R2 On R1.Customer_Guid = R2.Customer_Guid Where R1.Rec_Guid = ? And (R1.Status != If(Ifnull(R2.Customertype, '个人') = '公司', '4', '2') Or R1.Status Is Null Or R1.Status = '')", rec_Guid);
                log.debug("⚖法大大回调 认证回调 -查询是否还有未认证通过的客户-结果:" + selectExits);

                if (selectExits.size() == 0) {

                    // 记录主表批量处理进度
                    BatchData_Utils.updateStep(jt, "3", rec_Guid);

                    // 创建合同
                    JSONObject res_CreateCont = BatchDeal_Utils.createContract(jt, rec_Guid);
                    log.debug("生成合同完成-返回合同编号：" + res_CreateCont);

                    String res_Code = KHUtil.GetSFJV(res_CreateCont, "code");
                    if (res_Code.equals("1")) {
                        // 记录主表批量处理进度
                        BatchData_Utils.updateStep_APICode(jt, "3", KHUtil.GetSFJV(res_CreateCont, "code"), "认证全部完成-创建合同成功->推送签署ing", rec_Guid);
                        // 推送签署
                        JSONObject res_PushSign = BatchDeal_Utils.pushSign(jt, rec_Guid);
                        log.debug("推送签署返回对象：" + res_PushSign);
                    } else if (res_Code.equals("0")) {
                        log.warn("♻当前任务合同ID已经存在(合同疑似生成过,可能是已经关联认证回调或重复认证通过回调)");
                        // 推送签署
                        JSONObject res_PushSign = BatchDeal_Utils.pushSign(jt, rec_Guid);
                        log.debug("推送签署(重复认证)返回对象：" + res_PushSign);

                    } else {
                        // 记录主表创建合同进度
                        BatchData_Utils.updateStep_APICode(jt, "-3", KHUtil.GetSFJV(res_CreateCont, "code"), "创建合同错误:" + res_CreateCont, rec_Guid);

                    }

                } else {
                    // 存在暂未认证完成的用户
                    log.warn("⚖法大大回调 认证回调 -存在暂未认证完成的用户-数量:" + selectExits.size());

                    res_Json = JSONObject.fromObject(new FddResult(FddResult.SUCCESS, "认证回调处理完成", "存在暂未认证完成的用户"));
                }
            } else {
                log.warn("⚖法大大回调 认证回调 -出现认证失败的用户,任务计划结束-认证失败原因:" + auditFailReason);

                // 记录主表批量处理进度-失败
                BatchData_Utils.updateStep_APICode(jt, "-2", "-1", statusDesc + "(" + auditFailReason + "-任务结束)", rec_Guid);

                res_Json = JSONObject.fromObject(new FddResult(FddResult.SUCCESS, "认证回调处理完成", "出现认证失败的用户,任务计划结束"));
            }

            // 如果有认证回调需要通过用户ID检查是否有关联任务需要处理(只做触发,不管结果)
            BatchDeal_Utils.doAuthOtherCheck(jt, rec_Guid, Cc_CustomerId, callPram);

        } catch (Exception e) {
            // 合同数据认证回调处理异常
            BatchData_Utils.updateStep_APICode(jt, "-100", "-1", "FDD认证回调处理异常(" + e.getMessage() + ")", rec_Guid);

            res_Json = JSONObject.fromObject(new FddResult(FddResult.WARN, "认证回调处理异常(" + e.getMessage() + ")", ""));

            log.error("⚖法大大回调 认证回调 认证回调处理异常(" + e.getMessage() + ")", e);
        }

        return res_Json;
    }

}
